var ctx = window.daijia.ctx;
var address = window.daijia.address;
var iserrand = window.daijia.iserrand;
var ismainCompany = window.daijia.mainCompany;
var zhuanxian_map = null;
var driving = null;
var driving3 = null;
var distance = null;
var timeStr = null;
var startMarkers = null;
var endMarkers = null;
var addressPoint = new Array();
var orderType = null;//订单类型 id
var areaId = null;//类型对应的收费id
var endAdd = null;//目的地是否选填
var price = null;//价格
var baochePrice = null;//包车价格
var jihuoPrice = null;//寄货价格
var currentType = null//当前订单类型
var createFlag = false;
var lastEndAddress = "";
var lastStartAddress = "";
var zhuanxian_budgetPay = null;

function initializeMap() {
  var myGeo = new BMap.Geocoder();
  myGeo.getPoint(address, function (point) {
    if (point) {
      zhuanxian_map = new BMap.Map("zhuanxian_allmap");
      zhuanxian_map.centerAndZoom(point, 13);
      zhuanxian_map.enableScrollWheelZoom();
      zhuanxian_map.addEventListener("tilesloaded", function () {
        $(".anchorBL").remove();
      });
      //BMAP_DRIVING_POLICY_LEAST_TIME：最少时间，默认
      //BMAP_DRIVING_POLICY_LEAST_DISTANCE：最短距离
      //BMAP_DRIVING_POLICY_AVOID_HIGHWAYS：避开高速
      driving = new BMap.DrivingRoute(zhuanxian_map, {
        policy: BMAP_DRIVING_POLICY_LEAST_DISTANCE,
        onSearchComplete: function (results) {
          if (driving.getStatus() == BMAP_STATUS_SUCCESS) {
            // 获取第一条方案
            var plan = results.getPlan(0);
            distance = plan.getDistance();
            timeStr = plan.getDuration();
            getOrderType();
            getBudgetedExpensePrice();
          }
        },
        renderOptions: {    //显示到地图上
          map: zhuanxian_map,
          autoViewport: true
        }
      });

      //右键菜单
      var contextMenu = new BMap.ContextMenu();
      var txtMenuItem = [{
        text: '设为预约地',
        callback: function (p) {
          //zhuanxian_map.clearOverlays();清除所有覆盖物
          var gc = new BMap.Geocoder();
          gc.getLocation(p, function (rs) {
            console.debug(rs.addressComponents.city);
            if ($("#lineId").find("option:selected").attr("startcity").indexOf(
                rs.addressComponents.city) == -1) {
              return;
            }
            var startIcon = new BMap.Icon(ctx + "/assets/img/start.png",
                new BMap.Size(32, 33));
            var memberMarker = new BMap.Marker(p, {icon: startIcon});  // 创建标注
            zhuanxian_map.removeOverlay(startMarkers);
            startMarkers = memberMarker;
            zhuanxian_map.addOverlay(memberMarker);
            var addComp = rs.addressComponents;
            $("#zhuanxianStartAddress").val(
                addComp.street + " " + addComp.streetNumber);
            lastStartAddress = addComp.street
            $("#zhuanxian_startLat").val(p.lat);
            $("#zhuanxian_startLng").val(p.lng);
            var tempp = [p];

            if (endMarkers != null) {
              zhuanxian_map.clearOverlays();
              driving.search(p, endMarkers.getPosition());
              tempp[tempp.length] = endMarkers.getPosition();
              getZhuanxianEmployee();
            }
            setTimeout(function () {
              zhuanxian_map.setViewport(tempp);
              //调整到最佳视野
            }, 100);
          });
        }
      }, {
        text: '设为目的地',
        callback: function (p) {
          var gc = new BMap.Geocoder();
          gc.getLocation(p, function (rs) {
            var addComp = rs.addressComponents;
            if ($("#lineId").find("option:selected").attr("endcity").indexOf(
                rs.addressComponents.city) == -1) {
              var option = $("#lineId").find("option:selected");
              if ($("#zhuanxian_endLat").val() == "" || $(
                  "#zhuanxian_endLng").val() == "") {
                var city = option.attr("endcity") + option.attr("endaddress");
                if (city.trim() != "") {
                  zhuanxian_map.centerAndZoom(city, 13);
                  focusFlag = true;
                }
              }
              return;
            }
            var startIcon = new BMap.Icon(ctx + "/assets/img/end.png",
                new BMap.Size(32, 33));
            var memberMarker = new BMap.Marker(p, {icon: startIcon});  // 创建标注
            zhuanxian_map.removeOverlay(endMarkers);
            endMarkers = memberMarker;
            zhuanxian_map.addOverlay(memberMarker);
            $("#zhuanxianEndAddress").val(
                addComp.street + " " + addComp.streetNumber);
            lastEndAddress = addComp.street
            $("#zhuanxian_endLat").val(p.lat);
            $("#zhuanxian_endLng").val(p.lng);
            var tempp = [p];
            if (startMarkers != null) {
              zhuanxian_map.clearOverlays();
              driving.search(startMarkers.getPosition(), p);
              tempp[tempp.length] = startMarkers.getPosition();
              getZhuanxianEmployee();

            }
            setTimeout(function () {
              zhuanxian_map.setViewport(tempp);
              //调整到最佳视野
            }, 100);
          });
        }
      }];

      for (var i = 0; i < txtMenuItem.length; i++) {
        contextMenu.addItem(
            new BMap.MenuItem(txtMenuItem[i].text, txtMenuItem[i].callback,
                100));
        if (i == 1 || i == 3) {
          contextMenu.addSeparator();
        }
      }
      zhuanxian_map.addContextMenu(contextMenu);

    } else {
      $.scojs_message("地区" + address + "位置不准确,请重新编辑地区",
          $.scojs_message.TYPE_ERROR);
    }
  });

}

$("#zhuanxian_startTime").change(function () {
  getZhuanxianEmployee();
});

//推荐附近员工
function getZhuanxianEmployee() {
  if (($("#zhuanxian_startLat").val() != null && $("#zhuanxian_startLat").val()
      != "") && $("#zhuanxian_startLng").val() != null && $(
      "#zhuanxian_startLng").val() != "" && $("#lineId").val() != null && $(
      "#lineId").val() != "" && $("#zhuanxian_startTime").val() != "" && $(
      "#zhuanxian_startTime").val() != null) {
    var islimit = false;
    $.get(ctx + '/zhuanxian/getEmployees', {
      startLat: $("#zhuanxian_startLat").val(),
      startLng: $("#zhuanxian_startLng").val(),
      lineId: $("#lineId").val(),
      orderType: currentType,
      peopleNumber: $("#zhuanxian_peopleNumber").val(),
      serverTime: $("#zhuanxian_startTime").val(),
    }, function (data) {
      $(".zhuanxian_drivers-tr").remove();
      if (data && data.length > 0) {
        $(data).each(function (i, driver) {

          var content = "<tr class='zhuanxian_drivers-tr'>" +
              "<td><input type='" + (currentType == 1 ? "checkbox" : "radio")
              + "' name='zhuanxian_checkDriver' value='" + driver.employId
              + "' /></td>" +
              "<td>" + driver.employName + "</td>" +
              "<td>" + driver.carNumber + "</td>" +
              "<td>" + driver.distance + "</td>" +
              "<tr>";
          $("#zhuanxian_tbodyId").append(content);
        });
      }
    });
  } else {
    $(".zhuanxian_drivers-tr").remove();
  }
}

$(document).ready(function () {
  $("#zhuanxianClick").click(function () {
    initializeMap();
  });

  initializeMap();

  getPrice();

  $("#zhuanxian_startTime").val(
      new Date(new Date().getTime() + 1000 * 60 * 3).Format("yyyy-MM-dd hh:mm"))
  $("#zhuanxian_startTime").datetimepicker({
    format: 'yyyy-mm-dd HH:ii',
    language: 'zh-CN',
    minView: 'hour',
    pickDate: true,
    pickTime: false,
    inputMask: false,
    autoclose: true,
    startDate: new Date()
  });
  //公司修改后对应的车辆类型也修改
  $("#zhuanxian_companyId").change(function () {
    var companyId = $("#zhuanxian_companyId").val();
    $.get(ctx + '/zhuanxian/queryLines',
        {'companyId': companyId, 'deleteRepeat': 1}, function (data) {
          if (data.success) {
            console.log("test111");
            $("#lineId").html("");
            if (data.lines == null || data.lines.length == 0) {
              $("#lineId").append("<option value=''>该公司暂未设置线路</option>");
            }
            $(data.lines).each(function (index, line) {
              var id = line.id;
              var lineName = line.name;
              var company_name = "";
              if (data.company_main) {
                company_name = "&emsp;&emsp;&emsp;&emsp;" + line.companyName;
              }
              var text = "<option value=" + id + "   jihuoareaid='"
                  + line.jihuoAreaId + "' baocheareaid='" + line.baocheAreaId
                  + "' pingcheareaid='" + line.areaId + "' startcity='"
                  + line.startCity + "'  startaddress='" + line.startAddress
                  + "' endcity='" + line.endCity + "' endaddress='"
                  + line.endAddress + "'>" + lineName + company_name
                  + "</option>";
              $("#lineId").append(text);
            });

            if ($("#lineId").val() != "" && $("#lineId").val() != null
                && typeof ($("#lineId").val()) != undefined) {
              getPrice();
            } else {
              $("#zhuanxian_budgetPay").val("");
            }
            $("#lineId").change();
            getZhuanxianEmployee();
          }
        }, 'json');
  });

  /*$("#zhuanxian_couponId").change(function(){
    var type = $(this).find("option:selected").attr("c_type");
    var discount = $(this).find("option:selected").attr("c_discount");
    var money = $(this).find("option:selected").attr("c_money");
    if(zhuanxian_budgetPay!=null){
      if($(this).find("option:selected").val()==""){
        $("#zhuanxian_budgetPay").val(zhuanxian_budgetPay);
        return;
      }
      if(type==0){
        var temp = zhuanxian_budgetPay*(discount/10);
        if(temp<0){
          $("#zhuanxian_budgetPay").val(0);
        }else{
          $("#zhuanxian_budgetPay").val(temp);
        }

      }else if(type==1){
        var temp = zhuanxian_budgetPay-money;
        if(temp<0){
          $("#zhuanxian_budgetPay").val(0);
        }else{
          $("#zhuanxian_budgetPay").val(temp);
        }

      }
    }
  });*/
  $("#zhuanxian_passengerPhone").change(function () {
    $.get(ctx + '/member/findByPhone',
        {'phone': $(this).val(), 'couponType': 'zhuanxian'}, function (data) {
          if (data.passenger != null) {
            $("#zhuanxian_passengerId").val(data.passenger.id);
            $("#zhuanxian_passengerName").val(data.passenger.name);
            $("#zhuanxian_passengerPhone").val(data.passenger.phone);
            $("#zhuanxian_clientVirtual").text(
                data.passenger.drawMoney + data.passenger.nodrawMoney + "元");
            if (data.passenger.inBlackList) {
              $("#zhuanxian_membertype").html("黑名单");
            } else {
              $("#zhuanxian_membertype").html(data.passenger.typeStr);
            }
            if (ismainCompany == "true") {
              $("#zhuanxian_companyId option").each(function (index, element) {
                if ($(element).attr("value") == data.passenger.companyId) {
                  $(element).attr("selected", "selected");
                  return false;
                }
              });
            }
            var companyId = data.passenger.companyId;
            $("#zhuanxian_companyId").change();
            if (data.coupons != null && data.coupons.length > 0) {
              console.debug(data.coupons);
              var text = "<option value=''>" + "请选择优惠券" + "</option>";
              for (var i = 0; i < data.coupons.length; i++) {
                text += "<option value='" + data.coupons[i].id + "' c_type='"
                    + data.coupons[i].couponRule.type + "'   c_discount='"
                    + data.coupons[i].couponRule.discount + "'   c_money='"
                    + data.coupons[i].couponRule.money + "'>"
                    + data.coupons[i].couponRule.title + "</option>";
              }
              $("#zhuanxian_couponId").empty();
              if (text != "") {
                $("#zhuanxiancouponInput").css("display", "block");
                $("#zhuanxian_couponId").append(text);
              }

            } else {
              $("#zhuanxiancouponInput").css("display", "none");
              $("#zhuanxian_couponId").empty();
            }
          } else {
            $("#zhuanxiancouponInput").css("display", "none");
            $("#zhuanxian_couponId").empty();
            $("#zhuanxian_passengerId").val("");
            $("#zhuanxian_passengerName").val("先生/女士");
            $("#zhuanxian_membertype").html("新客户");
            $("#zhuanxian_clientVirtual").html("0元");
          }
        });

  });
  $("#lineId").change(function () {
    var option = $(this).find("option:selected");
    var city = option.attr("startcity") + option.attr("startaddress");
    if (city.trim() != "") {
      zhuanxian_map.centerAndZoom(city, 13);
    }
    $("#zhuanxianEndAddress").val("");
    $("#zhuanxian_endLat").val("");
    $("#zhuanxian_endLng").val("");
    $("#zhuanxianStartAddress").val("");
    $("#zhuanxian_startLat").val("");
    $("#zhuanxian_startLng").val("");
    startMarkers = null;
    endMarkers = null;
    zhuanxian_map.clearOverlays();
    getPrice();
    getZhuanxianEmployee();
  });
  var focusFlag = true;
  $("#zhuanxianEndAddress").focus(function () {
    var option = $("#lineId").find("option:selected");
    if ($("#zhuanxian_endLat").val() == "" || $("#zhuanxian_endLng").val()
        == "") {

      var city = option.attr("endcity") + option.attr("endaddress");
      if (city.trim() != "") {
        zhuanxian_map.centerAndZoom(city, 13);
        focusFlag = true;
      }
    } else {
      var p = new BMap.Point(parseFloat($("#zhuanxian_endLng").val()),
          parseFloat($("#zhuanxian_endLat").val()));
      zhuanxian_map.centerAndZoom(p, 13);
    }

  });

  $("#zhuanxianStartAddress").focus(function () {
    var option = $("#lineId").find("option:selected");
    /*var city = option.attr("startcity")+option.attr("startaddress");
    if(city.trim()!=""){
      zhuanxian_map.centerAndZoom(city,13);
    }*/
    if ($("#zhuanxian_startLat").val() == "" || $("#zhuanxian_startLng").val()
        == "") {
      var city = option.attr("startcity") + option.attr("startaddress");
      if (city.trim() != "") {
        zhuanxian_map.centerAndZoom(city, 13);
      }

    } else {
      var p = new BMap.Point(parseFloat($("#zhuanxian_startLng").val()),
          parseFloat($("#zhuanxian_startLat").val()));
      zhuanxian_map.centerAndZoom(p, 13);
    }

  });
  $("#zhuanxian_peopleNumber").change(function () {
    if (typeof (price) != undefined && price != null) {
      $("#zhuanxian_budgetPay").val(parseInt($(this).val()) * price);
    }
    getBudgetedExpensePrice();
    getZhuanxianEmployee();
  });

  $("#zhuanxian_saveOrder").click(function () {
    debugger
    getOrderType();
    if (createFlag) {
      return;
    }

    if (currentType == null || typeof (currentType) == undefined) {
      $.scojs_message("请选择订单类型", $.scojs_message.TYPE_ERROR);
      return;
    }
    if ($("#zhuanxian_passengerPhone").val() == '') {
      $.scojs_message("请填写客户电话", $.scojs_message.TYPE_ERROR);
      return;
    }
    if (ismainCompany == "true" && !$("#companyId3").val()) {
      $.scojs_message("请选择公司", $.scojs_message.TYPE_ERROR);
      return;
    }

    if ($("#zhuanxian_startTime").val() == '') {
      $.scojs_message("请填写预约时间", $.scojs_message.TYPE_ERROR);
      return;
    } else if (!/^(\d{4})\-(\d{2})\-(\d{2}) (\d{2}):(\d{2})$/.test(
        $("#zhuanxian_startTime").val())) {
      $.scojs_message("时间格式不正确,如" + new Date().Format("yyyy-MM-dd hh:ss"),
          $.scojs_message.TYPE_ERROR);
      return;
    } else {
      if (new Date($("#zhuanxian_startTime").val().replace("-", "/")).getTime()
          < new Date().getTime()) {
        $.scojs_message("预约时间请大于当前时间", $.scojs_message.TYPE_ERROR);
        return;
      }
    }
    if ($("#lineId").val() == '') {
      $.scojs_message("请选择线路", $.scojs_message.TYPE_ERROR);
      return;
    }
    if (($("#zhuanxian_peopleNumber").val() == '' && currentType == 0) || $(
        "#zhuanxian_peopleNumber").val() > 99) {
      $.scojs_message(
          $("#zhuanxian_peopleNumber").val() > 99 ? "乘坐人数不能大于99位" : "请填写乘坐人数",
          $.scojs_message.TYPE_ERROR);
      return;
    }

    if (($("#zhuanxian_peopleNumber").val() == '' && currentType == 1) || $(
        "#zhuanxian_peopleNumber").val() > 99) {
      $.scojs_message(
          $("#zhuanxian_peopleNumber").val() > 99 ? "包车车辆不能大于99辆" : "请填写包车车辆",
          $.scojs_message.TYPE_ERROR);
      return;
    }

    if (($("#zhuanxian_takeDeliveryName").val() == '' && currentType == 2)
        || ($("#zhuanxian_takeDeliveryPhone").val() == '' && currentType
            == 2)) {
      $.scojs_message("请填写收货人信息", $.scojs_message.TYPE_ERROR);
      return;
    }
    if ($("#zhuanxianStartAddress").val() == '') {
      $.scojs_message("请填写预约地", $.scojs_message.TYPE_ERROR);
      return;
    }
    if ($("#zhuanxian_startLat").val() == null || $("#zhuanxian_startLng").val()
        == null) {
      $.scojs_message("请先定位你的预约地", $.scojs_message.TYPE_ERROR);
      return false;
    }
    if ($("#zhuanxianEndAddress").val() == '') {
      $.scojs_message("请填写目的地", $.scojs_message.TYPE_ERROR);
      return;
    }
    if ($("#zhuanxian_endLat").val() == null || $("#zhuanxian_endLng").val()
        == null) {
      $.scojs_message("请先定位你的目的地", $.scojs_message.TYPE_ERROR);
      return false;
    }
    if (currentType == 1 && ($(
        "input[name=zhuanxian_checkDriver]:checked").length) > $(
        "#zhuanxian_peopleNumber").val()) {
      $.scojs_message("选择服务人员数量不能超过所需车辆数", $.scojs_message.TYPE_ERROR);
      return false;
    }
    var employId = "";
    var employArr = [];
    $("input[name=zhuanxian_checkDriver]:checked").each(
        function (index, element) {
          employArr.push($(element).val());
        });
    if (null != employArr && employArr.length > 0) {
      employId = employArr.join(",");
    }
    createFlag = true;
    if (ismainCompany) {
      $.post(ctx + "/zhuanxian/createOrder",
          {
            orderType: currentType,
            passengerId: $("#zhuanxian_passengerId").val(),
            passengerName: $("#zhuanxian_passengerName").val(),
            passengerPhone: $("#zhuanxian_passengerPhone").val(),
            companyId: $("#zhuanxian_companyId").val(),
            companyName: $("#zhuanxian_companyId").find(
                "option:selected").text(),
            startTime: $("#zhuanxian_startTime").val(),
            lineId: $("#lineId").val(),
            peopleNumber: currentType != 2 ? $("#zhuanxian_peopleNumber").val()
                : "",
            startAddress: $("#zhuanxianStartAddress").val(),
            startLat: $("#zhuanxian_startLat").val(),
            startLng: $("#zhuanxian_startLng").val(),
            endAddress: $("#zhuanxianEndAddress").val(),
            endLat: $("#zhuanxian_endLat").val(),
            endLng: $("#zhuanxian_endLng").val(),
            couponId: $("#zhuanxian_couponId").val(),
            budgetPay: $("#zhuanxian_budgetPay").val(),
            memo: $("#zhuanxian_orderMemo").val(),
            takeDeliveryName: currentType == 2 ? $(
                "#zhuanxian_takeDeliveryName").val() : "",
            takeDeliveryPhone: currentType == 2 ? $(
                "#zhuanxian_takeDeliveryPhone").val() : "",
            employId: employId
          }, function (data) {

            console.debug(data);
            if (data.success) {
              $.scojs_message("下单成功", $.scojs_message.TYPE_OK);
              issubmit = true;
              window.close();
              window.opener.location.reload(true);

            } else {
              $.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
            }
            createFlag = false;
          }).error(function () {
        createFlag = false;
      });
    } else {
      $.post(ctx + "/zhuanxian/createOrder",
          {
            orderType: currentType,
            passengerId: $("#zhuanxian_passengerId").val(),
            passengerName: $("#zhuanxian_passengerName").val(),
            passengerPhone: $("#zhuanxian_passengerPhone").val(),
            startTime: $("#zhuanxian_startTime").val(),
            lineId: $("#lineId").val(),
            peopleNumber: currentType != 2 ? $("#zhuanxian_peopleNumber").val()
                : "",
            startAddress: $("#zhuanxianStartAddress").val(),
            startLat: $("#zhuanxian_startLat").val(),
            startLng: $("#zhuanxian_startLng").val(),
            endAddress: $("#zhuanxianEndAddress").val(),
            endLat: $("#zhuanxian_endLat").val(),
            endLng: $("#zhuanxian_endLng").val(),
            couponId: $("#zhuanxian_couponId").val(),
            budgetPay: $("#zhuanxian_budgetPay").val(),
            memo: $("#zhuanxian_orderMemo").val(),
            takeDeliveryName: currentType == 2 ? $(
                "#zhuanxian_takeDeliveryName").val() : "",
            takeDeliveryPhone: currentType == 2 ? $(
                "#zhuanxian_takeDeliveryPhone").val() : "",
            employId: employId
          }, function (data) {

            console.debug(data);
            if (data.success) {
              $.scojs_message("下单成功", $.scojs_message.TYPE_OK);
              issubmit = true;
              window.close();
              window.opener.location.reload(true);

            } else {
              $.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
            }
            createFlag = false;
          }).error(function () {
        createFlag = false;
      });
    }

  });

  $("#zhuanxian_orderType li").click(function () {
    currentType = parseInt($(this).attr("val"));
    var type = currentType;
    if (type == 0) {
      $("#zhuanxian_peopleNumber").val(1);
      $("#zhuanxian_peopleNumber_text").text("乘车人数");
      $("#zhuanxian_peopleNumber_text_addon").text("位");
      $("#zhuanxian_peopleNumber_div").show();
      $("#zhuanxian_startTime_text").text("预约时间");
      /* if(typeof(price) != undefined && price  != null){
        $("#zhuanxian_budgetPay").val(parseInt($("#zhuanxian_peopleNumber").val())*price);
      }*/
      $("#zhuanxianTakeDelivery_div").hide();
    } else if (type == 1) {
      $("#zhuanxian_peopleNumber").val(1);
      $("#zhuanxian_peopleNumber_text").text("包车车辆");
      $("#zhuanxian_peopleNumber_text_addon").text("辆");
      $("#zhuanxian_peopleNumber_div").show();
      $("#zhuanxian_startTime_text").text("预约时间");
      /* if(typeof(baochePrice) != undefined && baochePrice  != null){
        $("#zhuanxian_budgetPay").val(baochePrice);
      }*/
      $("#zhuanxianTakeDelivery_div").hide();
    } else if (type == 2) {
      /* if(typeof(jihuoPrice) != undefined && jihuoPrice  != null){
        $("#zhuanxian_budgetPay").val(jihuoPrice);
      } */
      $("#zhuanxian_peopleNumber_text_addon").text("位");
      $("#zhuanxian_peopleNumber").val(1);
      $("#zhuanxian_peopleNumber_div").hide();
      $("#zhuanxian_startTime_text").text("寄货时间");
      $("#zhuanxianTakeDelivery_div").show();
    }
    getBudgetedExpensePrice();
    getZhuanxianEmployee();
  });
  $("#zhuanxian_wanghuan").click(function () {
    var startLng = $("#zhuanxian_startLng").val();
    var startLat = $("#zhuanxian_startLat").val();
    var startAddress = $("#zhuanxianStartAddress").val();
    $("#zhuanxian_startLng").val($("#zhuanxian_endLng").val());
    $("#zhuanxian_startLat").val($("#zhuanxian_endLat").val());
    $("#zhuanxianStartAddress").val($("#zhuanxianEndAddress").val());
    $("#zhuanxian_endLng").val(startLng);
    $("#zhuanxian_endLat").val(startLat);
    $("#zhuanxianEndAddress").val(startAddress);
    var starts = startMarkers;
    startMarkers = endMarkers;
    endMarkers = starts;
    if (startMarkers != null && endMarkers != null) {
      zhuanxian_map.clearOverlays();
      driving.search(startMarkers.getPosition(), endMarkers.getPosition());
    }
    getZhuanxianEmployee();
  })

  $("#btn-zhuanxianStartAddress").click(function () {
    if ($("#zhuanxianStartAddress").val() == '') {
      $.scojs_message("请填写预约地", $.scojs_message.TYPE_ERROR);
    } else {
      var local = new BMap.LocalSearch(zhuanxian_map, {
        renderOptions: {map: zhuanxian_map, autoViewport: true}
      });
      var option = $("#lineId").find("option:selected");
      var city = option.attr("startcity") + option.attr("startaddress");
      zhuanxian_map.clearOverlays();
      local.search(city + $("#zhuanxianStartAddress").val());
      local.setInfoHtmlSetCallback(function (poi, html) {
        $("#zhuanxianStartAddress").val(poi.title)
        $("#zhuanxian_startLat").val(poi.marker.point.lat);
        $("#zhuanxian_startLng").val(poi.marker.point.lng);
        var startIcon = new BMap.Icon(ctx + "/assets/img/start.png",
            new BMap.Size(32, 33));
        var marker = new BMap.Marker(poi.marker.point, {icon: startIcon});
        zhuanxian_map.removeOverlay(startMarkers);
        startMarkers = marker;
        //zhuanxian_map.addOverlay(marker);
        var tempp = [poi.marker.point];
        if (endMarkers != null) {
          tempp[tempp.length] = endMarkers.getPosition();
          driving.search(poi.marker.point, endMarkers.getPosition());
          getZhuanxianEmployee();
        }
        /*setTimeout(function(){
              zhuanxian_map.setViewport(tempp);
              //调整到最佳视野
          },2000);*/
      });
    }
  });
  $("#btn-zhuanxianEndAddress").click(function () {
    if ($("#zhuanxianEndAddress").val() == '') {
      $.scojs_message("请填写目的地", $.scojs_message.TYPE_ERROR);
    } else {
      var local = new BMap.LocalSearch(zhuanxian_map, {
        renderOptions: {map: zhuanxian_map, autoViewport: true}
      });

      var option = $("#lineId").find("option:selected");
      var city = option.attr("endcity") + option.attr("endaddress");
      zhuanxian_map.clearOverlays();
      local.search(city + $("#zhuanxianEndAddress").val());
      local.setInfoHtmlSetCallback(function (poi, html) {
        $("#zhuanxianEndAddress").val(poi.title)
        $("#zhuanxian_endLat").val(poi.marker.point.lat);
        $("#zhuanxian_endLng").val(poi.marker.point.lng);
        var endIcon = new BMap.Icon(ctx + "/assets/img/end.png",
            new BMap.Size(32, 33));
        var marker = new BMap.Marker(poi.marker.point, {icon: endIcon});
        zhuanxian_map.removeOverlay(endMarkers);
        endMarkers = marker;
        //	zhuanxian_map.addOverlay(marker);
        var tempp = [poi.marker.point];
        if (startMarkers != null) {
          driving.search(startMarkers.getPosition(), poi.marker.point);
          tempp[tempp.length] = startMarkers.getPosition();
          getZhuanxianEmployee();
        }
        /*setTimeout(function(){
          zhuanxian_map.setViewport(tempp);
          //调整到最佳视野
        },2000);*/
      });
    }
  });

});

$("#zhuanxianStartAddress").AutoComplete({
  data: ctx + "/zhuanxian/getHistoryInputedPlace",
  ajaxDataType: "json",
  itemHeight: 24,
  max: 1,
  ajaxParams: function (keyword) {
    var option = $("#lineId").find("option:selected");
    var city = option.attr("startcity");
    var temp = city.split("-");
    if (temp.length > 1) {
      city = temp[1];
    } else {
      city = temp[0];
    }
    return {'city': city};
  },
  width: "auto",
  async: true,
  listStyle: "custom",
  emphasis: false,
  matchHandler: function (keyword, data) {
    return true;
  },
  createItemHandler: function (index, data) {
    if (data.address.length > 14) {
      return "<span title='" + data.address + "'>" + data.address.substring(0,
          14) + "</span>";
    }
    return "<span title='" + data.address + "'>" + data.address + "</span>";
  },
  afterSelectedHandler: function (data) {
    //	var address = (data.address).split(" ");
    var gc = new BMap.Geocoder();
    var p = new BMap.Point(data.longitude, data.latitude);
    gc.getLocation(p, function (rs) {
      console.debug(rs.addressComponents.city);
      if ($("#lineId").find("option:selected").attr("startcity").indexOf(
          rs.addressComponents.city) == -1) {
        $("#zhuanxianStartAddress").val(lastStartAddress);
      } else {
        $("#zhuanxianStartAddress").val(data.address);
        lastStartAddress = data.address;
        $("#zhuanxian_startLat").val(data.latitude);
        $("#zhuanxian_startLng").val(data.longitude);

        var p = new BMap.Point(data.longitude, data.latitude);
        var startIcon = new BMap.Icon(ctx + "/assets/img/start.png",
            new BMap.Size(32, 33));
        var marker = new BMap.Marker(p, {icon: startIcon});
        zhuanxian_map.removeOverlay(startMarkers);
        startMarkers = marker;
        zhuanxian_map.addOverlay(marker);
        var tempp = [p];
        if (endMarkers != null) {
          zhuanxian_map.clearOverlays();
          driving.search(p, endMarkers.getPosition());
          tempp[tempp.length] = endMarkers.getPosition();
          getZhuanxianEmployee();
        }
        setTimeout(function () {
          zhuanxian_map.setViewport(tempp);
          //调整到最佳视野
        }, 100);
      }

    });

  }
}).AutoComplete('show');

$("#zhuanxianEndAddress").AutoComplete({
  data: ctx + "/zhuanxian/getHistoryInputedPlace",
  ajaxDataType: "json",
  itemHeight: 24,
  ajaxParams: function (keyword) {
    var option = $("#lineId").find("option:selected");
    var city = option.attr("endcity");
    var temp = city.split("-");
    if (temp.length > 1) {
      city = temp[1];
    } else {
      city = temp[0];
    }
    return {'city': city};
  },
  max: 1,
  width: "auto",
  async: true,
  listStyle: "custom",
  emphasis: false,
  matchHandler: function (keyword, data) {
    return true;
  },
  createItemHandler: function (index, data) {
    if (data.address.length > 14) {
      return "<span title='" + data.address + "'>" + data.address.substring(0,
          14) + "</span>";
    }
    return "<span title='" + data.address + "'>" + data.address + "</span>";
  },
  afterSelectedHandler: function (data) {
    //	var address = (data.address).split(" ");

    var p = new BMap.Point(data.longitude, data.latitude);
    var gc = new BMap.Geocoder();
    gc.getLocation(p, function (rs) {
      console.debug(rs.addressComponents.city);
      if ($("#lineId").find("option:selected").attr("endcity").indexOf(
          rs.addressComponents.city) == -1) {
        $("#zhuanxianEndAddress").val(lastEndAddress);
      } else {
        $("#zhuanxianEndAddress").val(data.address);
        lastEndAddress = data.address;
        $("#zhuanxian_endLat").val(data.latitude);
        $("#zhuanxian_endLng").val(data.longitude);
        var p = new BMap.Point(data.longitude, data.latitude);
        var startIcon = new BMap.Icon(ctx + "/assets/img/end.png",
            new BMap.Size(32, 33));
        var marker = new BMap.Marker(p, {icon: startIcon});
        zhuanxian_map.removeOverlay(endMarkers);
        endMarkers = marker;
        zhuanxian_map.addOverlay(marker);
        var tempp = [p];
        if (startMarkers != null) {
          zhuanxian_map.clearOverlays();
          driving.search(startMarkers.getPosition(), p);
          tempp[tempp.length] = startMarkers.getPosition();
          getZhuanxianEmployee();
        }
        setTimeout(function () {
          zhuanxian_map.setViewport(tempp);
          //调整到最佳视野
        }, 100);
      }

    });

  }
}).AutoComplete('show');

function getBudgetedExpensePrice() {
  var areaId;
  var type = currentType;

  if (timeStr != null && distance != null) {
    if (type == 0) {
      areaId = $("#lineId").find("option:selected").attr("pingcheareaid");
    } else if (type == 1) {
      areaId = $("#lineId").find("option:selected").attr("baocheareaid");
    } else if (type == 2) {
      areaId = $("#lineId").find("option:selected").attr("jihuoareaid");
    }
    console.debug($("#lineId"));
    $.post(ctx + "/zhuanxian/getBudgetedExpensePrice",
        {
          areaId: areaId,
          time: timeStr,
          mileage: distance
        }, function (data) {
          $("#shouldPay").val(data.money);
          $("#startPrice").val(data.startPrice);
          $("#mileagePrice").val(data.mileagePrice);
          $("#travelTimePrice").val(data.travelTimePrice);
          $("#travelTime").val(data.travelTime);
          $("#mileage").val(data.mileage);
          $(".mileage_text").text("预计路程:" + data.mileage + "公里");
          $(".travelTime_text").text("预计时间:" + data.travelTime + "分钟");
          if (getOrderType() != 2) {
            $("#zhuanxian_budgetPay").val((parseInt(
                $("#zhuanxian_peopleNumber").val() == "" || $(
                    "#zhuanxian_peopleNumber").val() == undefined ? 1 : $(
                    "#zhuanxian_peopleNumber").val()) * data.money).toFixed(2));
            zhuanxian_budgetPay = parseInt(
                $("#zhuanxian_peopleNumber").val() == "" || $(
                    "#zhuanxian_peopleNumber").val() == undefined ? 1 : $(
                    "#zhuanxian_peopleNumber").val()) * data.money;
          } else {
            $("#zhuanxian_budgetPay").val(data.money.toFixed(2));
            zhuanxian_budgetPay = data.money;
          }
          $("#zhuanxian_couponId").change();
        }, "json");
  }

}

/*function getBudgetedExpensePrice(){
	var areaId;
	
	if(timeStr!=null && distance!=null){
		if(getOrderType()==0){
			areaId = $("#lineId").find("option:selected").attr("pingcheareaid");
		}else if(getOrderType()==1){
			areaId = $("#lineId").find("option:selected").attr("baocheareaid");
		}else if(getOrderType()==2){
			areaId = $("#lineId").find("option:selected").attr("jihuoareaid");
		}
		console.debug($("#lineId"));
		 $.post(ctx+"/zhuanxian/getBudgetedExpensePrice",
				   {areaId:areaId,
				    time:timeStr,
				    mileage:distance},function(data){							    	
				    	$("#shouldPay").val(data.money);
				    	$("#startPrice").val(data.startPrice);
				    	$("#mileagePrice").val(data.mileagePrice);
				    	$("#travelTimePrice").val(data.travelTimePrice);
				    	$("#travelTime").val(data.travelTime);
				    	$("#mileage").val(data.mileage);
				    	$(".mileage_text").text("预计路程:"+data.mileage+"公里");
				    	$(".travelTime_text").text("预计时间:"+data.travelTime+"分钟");
				    	if(getOrderType()!=2){
				    		$("#zhuanxian_budgetPay").val(parseInt($("#zhuanxian_peopleNumber").val()=="" || $("#zhuanxian_peopleNumber").val()==undefined ?1:$("#zhuanxian_peopleNumber").val())*data.money);
				    	}else{
				    		$("#zhuanxian_budgetPay").val(data.money);
				    	}
				    	//$("#zhuanxian_budgetPay").val(parseInt($("#zhuanxian_peopleNumber").val())*data.money);
				    	
				    },"json");	
	}
	
}*/
function getPrice() {
  $.post(ctx + "/zhuanxian/getPrice",
      {lineId: $("#lineId").val()}, function (data) {
        price = data.money;
        baochePrice = data.baocheMoney;
        jihuoPrice = data.jihuoMoney;
        var type = getOrderType();
        if (type == 0) {
          /* if(typeof(price) != undefined && price  != null){
            $("#zhuanxian_budgetPay").val(parseInt($("#zhuanxian_peopleNumber").val())*price);
          }*/
          $("#zhuanxian_peopleNumber_text").text("乘车人数");
          $("#zhuanxian_peopleNumber_text_addon").text("位");
          $("#zhuanxian_peopleNumber_div").show();
          $("#zhuanxian_startTime_text").text("预约时间");
          $("#zhuanxianTakeDelivery_div").hide();
        } else if (type == 1) {
          /* if(typeof(baochePrice) != undefined && baochePrice  != null){
            $("#zhuanxian_budgetPay").val(baochePrice);
          }*/
          $("#zhuanxian_peopleNumber_text").text("包车车辆");
          $("#zhuanxian_peopleNumber_text_addon").text("辆");
          $("#zhuanxian_peopleNumber_div").show();
          $("#zhuanxian_startTime_text").text("预约时间");
          /* if(typeof(baochePrice) != undefined && baochePrice  != null){
            $("#zhuanxian_budgetPay").val(parseInt($("#zhuanxian_peopleNumber").val())*baochePrice);
          }*/
          $("#zhuanxianTakeDelivery_div").hide();
        } else if (type == 2) {
          /*  if(typeof(jihuoPrice) != undefined && jihuoPrice  != null){
             $("#zhuanxian_budgetPay").val(jihuoPrice);
           } */
          $("#zhuanxian_peopleNumber_text").text("乘车人数");
          $("#zhuanxian_peopleNumber_text_addon").text("位");
          $("#zhuanxian_peopleNumber").val("");
          $("#zhuanxian_peopleNumber_div").hide();
          $("#zhuanxian_startTime_text").text("寄货时间");
          $("#zhuanxianTakeDelivery_div").show();
        }
        getBudgetedExpensePrice();
      }, "json");
}

function getOrderType() {
  var type = null;
  var li = $("#zhuanxian_orderType li[class=active]")[0];
  type = $(li).attr("val");
  currentType = type;
  return parseInt(type);
}

Date.prototype.Format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1,                 //月份
    "d+": this.getDate(),                    //日
    "h+": this.getHours(),                   //小时
    "m+": this.getMinutes(),                 //分
    "s+": this.getSeconds(),                 //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds()             //毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1,
        (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1,
          (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(
              ("" + o[k]).length)));
    }
  }
  return fmt;
}
